<template>
  <div class="app-wrapper">
    <McLayout class="container">
      <!-- Header 区域 -->
      <McHeader :title="'智能客服'" :logoImg="'/logo.svg'">
        <template #operationArea>
          <div class="operations">
            <span class="status-dot"></span>
            <span class="status-text">在线服务</span>
          </div>
        </template>
      </McHeader>

      <!-- 欢迎页面 -->
      <McLayoutContent v-if="startPage" class="intro-container">
        <McIntroduction :logoImg="'/logo.svg'" :title="'智能客服'" :subTitle="'Hi，欢迎使用MateChat智能客服'" :description="description">
        </McIntroduction>
        <McPrompt :list="introPrompt.list" :direction="introPrompt.direction" class="intro-prompt"
          @itemClick="onSubmit($event.label)"></McPrompt>
      </McLayoutContent>

      <!-- 对话内容区域 -->
      <McLayoutContent class="content-container" v-else>
        <template v-for="(msg, idx) in messages" :key="idx">
          <!-- 用户消息 -->
          <McBubble v-if="msg.from === 'user'" :content="msg.content" :align="'right'"
            :avatarConfig="{ imgSrc: '/logo.svg' }">
          </McBubble>

          <!-- AI 消息 -->
          <McBubble v-else :content="formatMessage(msg.content)" :avatarConfig="{ imgSrc: '/logo.svg' }"
            :loading="msg.loading">
            <!-- 自定义内容：订单信息卡片 -->
            <template v-if="msg.type === 'orderInfo'">
              <div class="order-info-card">
                <div class="order-info-item">
                  <span class="order-info-label">订单号：</span>
                  <span class="order-info-value">{{ msg.data.orderNo }}</span>
                </div>
                <div class="order-info-item">
                  <span class="order-info-label">商品：</span>
                  <span class="order-info-value">{{ msg.data.productName }}</span>
                </div>
                <div class="order-info-item">
                  <span class="order-info-label">金额：</span>
                  <span class="order-info-value">¥{{ msg.data.amount }}</span>
                </div>
                <div class="order-info-item">
                  <span class="order-info-label">状态：</span>
                  <span class="order-info-value">{{ msg.data.status }}</span>
                </div>
              </div>
              <div class="action-buttons" v-if="msg.actions">
                <d-button v-for="(action, idx) in msg.actions" :key="idx" :variant="action.primary ? 'solid' : 'text'"
                  :color="action.primary ? 'primary' : 'secondary'" @click="handleActionClick(action, msg)" size="sm">
                  {{ action.label }}
                </d-button>
              </div>
            </template>

            <!-- 自定义内容：物流时间线 / 退款进度 -->
            <template v-else-if="msg.type === 'logistics' || msg.type === 'refundProgress'">
              <div class="timeline-container" :class="{ 'refund-timeline': msg.type === 'refundProgress' }">
                <div class="timeline-header" v-if="msg.type === 'refundProgress'">
                  <i class="icon icon-info-o"></i>
                  <span class="timeline-title">退款进度</span>
                </div>
                <div class="logistics-timeline">
                  <div v-for="(item, idx) in msg.data.timeline" :key="idx"
                    :class="['timeline-item', { active: idx === 0 }]">
                    <div class="timeline-dot-wrapper">
                      <div class="timeline-dot"></div>
                      <div class="timeline-line" v-if="idx < msg.data.timeline.length - 1"></div>
                    </div>
                    <div class="timeline-content">
                      <div class="timeline-text">{{ item.text }}</div>
                      <div class="timeline-time">{{ item.time }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </template>

            <!-- 自定义内容：退货流程步骤 -->
            <template v-else-if="msg.type === 'returnSteps'">
              <div class="return-steps-container">
                <div class="return-steps-header">
                  <i class="icon icon-shopping-cart"></i>
                  <span class="return-steps-title">退货流程</span>
                </div>
                <div class="return-steps">
                  <div class="step-item" v-for="(step, idx) in msg.data.steps" :key="idx">
                    <div class="step-number">{{ idx + 1 }}</div>
                    <div class="step-content">
                      <i :class="['icon', step.icon, 'step-icon']"></i>
                      <span class="step-text">{{ step.text }}</span>
                    </div>
                  </div>
                </div>
              </div>
              <div class="action-buttons" v-if="msg.actions">
                <d-button v-for="(action, idx) in msg.actions" :key="idx" :variant="action.primary ? 'solid' : 'text'"
                  :color="action.primary ? 'primary' : 'secondary'" @click="handleActionClick(action, msg)" size="sm">
                  {{ action.label }}
                </d-button>
              </div>
            </template>
          </McBubble>
        </template>
      </McLayoutContent>

      <!-- 快捷指令区域 -->
      <div class="shortcut" v-if="!startPage">
        <McPrompt :list="simplePrompt" :direction="'horizontal'" style="flex: 1" @itemClick="onSubmit($event.label)">
        </McPrompt>
        <d-button icon="add" shape="circle" title="新建对话" size="md" @click="newConversation" />
      </div>

      <!-- 输入区域 -->
      <McLayoutSender>
        <McInput :value="inputValue" :maxLength="2000" @change="(e) => (inputValue = e)" @submit="onSubmit">
          <template #extra>
            <div class="input-foot-wrapper">
              <div class="input-foot-left">
                <span>{{ inputValue.length }}/2000</span>
              </div>
              <div class="input-foot-right">
                <d-button style="height: 32px;" icon="op-clearup" shape="round" :disabled="!inputValue" @click="inputValue = ''" size="sm">
                  清空输入
                </d-button>
              </div>
            </div>
          </template>
        </McInput>
      </McLayoutSender>
    </McLayout>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import { chatService } from './services/chatService'
import { promptList } from './config/prompts'
import { formatMessage } from './utils/messageFormatter'

const description = [
  '智能客服可以帮您处理订单查询、物流跟踪、退换货申请、优惠券问题等。',
  '作为AI助手，我会尽力为您提供准确的信息，如有疑问可随时转接人工客服。',
]

// 确保所有快捷指令都包含图标配置
const introPrompt = {
  direction: 'horizontal',
  list: promptList.map(item => {
    // 确保每个项都有完整的配置，包括图标
    if (!item.iconConfig) {
      console.warn(`快捷指令 "${item.label}" 缺少图标配置`)
    }
    return {
      value: item.value,
      label: item.label,
      desc: item.desc,
      iconConfig: item.iconConfig || { name: 'icon-helping', color: '#5e7ce0' } // 默认图标
    }
  })
}

const simplePrompt = promptList.map(item => {
  // 确保每个项都有图标配置
  if (!item.iconConfig) {
    console.warn(`快捷指令 "${item.label}" 缺少图标配置`)
  }
  return {
    value: item.value,
    iconConfig: item.iconConfig || { name: 'icon-helping', color: '#5e7ce0' }, // 默认图标
    label: item.label
  }
})

const startPage = ref(true)
const inputValue = ref('')
const messages = ref([])

// 新建对话
const newConversation = () => {
  startPage.value = true
  messages.value = []
  inputValue.value = ''
}

// 提交消息
const onSubmit = async (evt) => {
  const text = typeof evt === 'string' ? evt : evt.label || inputValue.value
  if (!text.trim()) return

  inputValue.value = ''
  startPage.value = false

  // 用户发送消息
  messages.value.push({
    from: 'user',
    content: text,
    avatarConfig: { imgSrc: '/logo.svg' }
  })

  // 调用 AI 服务
  await fetchData(text)
}

// 调用 AI 服务
const fetchData = async (ques) => {
  // 添加加载中的消息
  messages.value.push({
    from: 'model',
    content: '',
    avatarConfig: { imgSrc: '/logo.svg' },
    id: '',
    loading: true
  })

  try {
    // 使用流式返回
    const response = await chatService.sendMessage(ques, messages.value, true)

    // 更新最后一条消息
    const lastMsg = messages.value[messages.value.length - 1]
    lastMsg.loading = false
    lastMsg.content = response.content
    lastMsg.id = response.id

    // 解析响应，判断是否需要结构化展示
    const parsedMsg = parseAIResponse(response, ques)
    Object.assign(lastMsg, parsedMsg)

    // 滚动到底部
    nextTick(() => {
      const container = document.querySelector('.content-container')
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    })
  } catch (error) {
    console.error('发送消息失败:', error)
    const lastMsg = messages.value[messages.value.length - 1]
    lastMsg.loading = false
    lastMsg.content = '抱歉，服务暂时不可用，请稍后再试。如需帮助，请联系人工客服。'
  }
}

// 解析 AI 响应，判断消息类型
const parseAIResponse = (response, userQuery) => {
  const message = {
    content: response.content || response,
    type: 'text'
  }

  // 检测退款进度意图
  if (userQuery.includes('退款进度') || userQuery.includes('退款状态') || (userQuery.includes('退款') && userQuery.includes('进度'))) {
    message.type = 'refundProgress'
    message.data = {
      timeline: [
        { text: '退款已到账，请注意查收', time: '2024-01-16 10:30' },
        { text: '退款已处理，正在打款中', time: '2024-01-15 14:20' },
        { text: '退款申请已审核通过', time: '2024-01-14 16:00' },
        { text: '退款申请已提交，等待审核', time: '2024-01-13 09:15' }
      ]
    }
    return message
  }

  // 检测退货流程意图
  if (userQuery.includes('退货') || (userQuery.includes('退款') && !userQuery.includes('进度'))) {
    message.type = 'returnSteps'
    message.data = {
      steps: [
        { icon: 'icon-order', text: '进入【我的订单】，选择要退货的商品' },
        { icon: 'icon-upload', text: '上传商品照片及问题说明' },
        { icon: 'icon-check', text: '提交申请，等待审核（通常1个工作日内）' }
      ]
    }
    message.actions = [
      { label: '立即处理', primary: true, action: 'goToOrderPage' },
      { label: '查看退货政策', primary: false, action: 'showPolicy' }
    ]
    return message
  }

  // 检测物流查询意图
  if (userQuery.includes('物流') || userQuery.includes('快递') || userQuery.includes('发货')) {
    message.type = 'logistics'
    message.data = {
      timeline: [
        { text: '您的包裹已到达【北京分拨中心】，正在发往目的地', time: '2024-01-15 14:30' },
        { text: '您的包裹已从【上海仓库】发出', time: '2024-01-14 10:20' },
        { text: '您的订单已打包完成，等待发货', time: '2024-01-14 09:15' },
        { text: '您的订单已确认，正在备货', time: '2024-01-13 16:00' }
      ]
    }
    return message
  }

  // 检测订单查询意图
  if (userQuery.includes('订单') && (userQuery.includes('状态') || userQuery.includes('查询'))) {
    message.type = 'orderInfo'
    message.data = {
      orderNo: 'ORD20240115001',
      productName: 'iPhone 15 Pro Max 256GB',
      amount: '8999.00',
      status: '已发货'
    }
    message.actions = [
      { label: '查看物流', primary: true, action: 'viewLogistics' },
      { label: '申请售后', primary: false, action: 'applyAfterSale' }
    ]
    return message
  }

  // 检测是否需要人工转接
  if (response.needHuman || messages.value.filter(m => m.from === 'user').length > 5) {
    message.actions = [
      { label: '转接人工客服', primary: true, action: 'transferToHuman' }
    ]
  }

  return message
}

// 处理操作按钮点击
const handleActionClick = (action, message) => {
  switch (action.action) {
    case 'goToOrderPage':
      window.open('/orders', '_blank')
      break
    case 'showPolicy':
      messages.value.push({
        from: 'model',
        content: '退货政策：\n1. 7天无理由退货\n2. 商品需保持原包装\n3. 退款将在1-3个工作日内到账',
        avatarConfig: { imgSrc: '/logo.svg' }
      })
      break
    case 'viewLogistics':
      onSubmit('帮我查一下最近订单的物流信息')
      break
    case 'applyAfterSale':
      onSubmit('我想申请退货，需要什么流程？')
      break
    case 'transferToHuman':
      messages.value.push({
        from: 'model',
        content: '正在为您转接人工客服，请稍候...',
        avatarConfig: { imgSrc: '/logo.svg' }
      })
      break
  }
}
</script>

<style scoped>
.app-wrapper {
  width: 100%;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background: #f5f5f5;
}

.container {
  width: 100%;
  max-width: 1200px;
  height: calc(100vh - 40px);
  max-height: 900px;
  min-height: 600px;
  margin: 0 auto;
  padding: 0;
  gap: 0;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-wrapper {
    padding: 10px;
  }

  .container {
    height: calc(100vh - 20px);
    max-height: none;
    border-radius: 12px;
  }

  .intro-container {
    padding: 40px 20px;
  }

  .content-container {
    padding: 16px;
  }
}

.intro-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12px;
  padding: 60px 40px;
  flex: 1;
  overflow: auto;
}

.intro-prompt {
  max-width: 1000px;
  width: 100%;
  margin: 20px auto 0;
  display: flex;
  justify-content: center;
}

/* 快捷指令卡片等宽显示 - 欢迎页面 */
.intro-prompt :deep(.mc-list .mc-list-item) {
  flex: 0 0 calc(33.333% - 12px);
}

.intro-prompt :deep(.mc-prompt) {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 16px;
  width: 100%;
}

.intro-prompt :deep(.mc-prompt-item) {
  flex: 0 0 calc(33.333% - 12px);
  min-width: 200px;
  max-width: 300px;
  box-sizing: border-box;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .intro-prompt :deep(.mc-prompt-item) {
    flex: 0 0 calc(50% - 8px);
    max-width: 350px;
  }
}

@media (max-width: 768px) {
  .intro-prompt :deep(.mc-prompt-item) {
    flex: 0 0 calc(50% - 8px);
    min-width: 160px;
    max-width: 300px;
  }
}

@media (max-width: 480px) {
  .intro-prompt :deep(.mc-prompt-item) {
    flex: 0 0 100%;
    max-width: 100%;
  }
}

.content-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
  overflow: auto;
  padding: 24px;
  flex: 1;
  background: #f8f9fa;
}

@keyframes pulse {

  0%,
  100% {
    opacity: 1;
    transform: scale(1);
  }

  50% {
    opacity: 0.7;
    transform: scale(1.1);
  }
}

/* Header 样式优化 */
:deep(.mc-header) {
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  flex-shrink: 0;
  padding: 16px 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

:deep(.mc-header .mc-header-title) {
  color: #fff;
  font-weight: 600;
  font-size: 18px;
}

:deep(.mc-header .header-logo) {
  filter: brightness(0) invert(1);
}

.operations {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
}

.operations:hover {
  background: rgba(255, 255, 255, 0.3);
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #52c41a;
  animation: pulse 2s infinite;
  box-shadow: 0 0 8px rgba(82, 196, 26, 0.6);
}

.status-text {
  font-size: 14px;
  color: #fff;
  font-weight: 500;
}

/* 输入区域样式优化 */
:deep(.mc-layout-sender) {
  border-top: 1px solid #e8e8e8;
  background: #fff;
  flex-shrink: 0;
  padding: 16px 24px;
}

.shortcut {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  border-top: 1px solid #e8e8e8;
  background: #fff;
  flex-shrink: 0;
}

/* 对话中的快捷指令样式 */
.shortcut :deep(.mc-prompt) {
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  gap: 8px;
}

.shortcut :deep(.mc-prompt-item) {
  flex: 0 0 auto;
  min-width: auto;
  max-width: none;
}

.input-foot-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 100%;
  margin-right: 8px;
}

.input-foot-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.input-foot-left span {
  font-size: 14px;
  color: #71757f;
}

.input-foot-right {
  display: flex;
  align-items: center;
}

/* 清空输入按钮样式优化 */
.clear-input-btn {
  transition: all 0.3s ease;
  border: 1px solid #e8e8e8;
  background: #fff;
  color: #666;
}

.clear-input-btn:hover:not(:disabled) {
  background: #f5f5f5;
  border-color: #d9d9d9;
  color: #333;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.clear-input-btn:active:not(:disabled) {
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.clear-input-btn:disabled {
  opacity: 0.4;
  cursor: not-allowed;
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

/* 电商场景定制样式 */
.order-info-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  margin: 12px 0;
}

.order-info-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #e8e8e8;
}

.order-info-item:last-child {
  border-bottom: none;
}

.order-info-label {
  color: #666;
  font-size: 14px;
}

.order-info-value {
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

/* 物流时间线 / 退款进度样式优化 */
.timeline-container {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  margin: 12px 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.timeline-container.refund-timeline {
  background: linear-gradient(135deg, #fffbf0 0%, #fff 100%);
  border: 1px solid #ffe8cc;
  box-shadow: 0 2px 8px rgba(245, 158, 11, 0.08);
}

.timeline-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #ffe8cc;
}

.timeline-header .icon {
  font-size: 20px;
  color: #f59e0b;
}

.timeline-title {
  font-size: 16px;
  font-weight: 600;
  color: #f59e0b;
}

.logistics-timeline {
  padding: 8px 0;
}

.timeline-item {
  display: flex;
  align-items: flex-start;
  padding: 16px 0;
  position: relative;
  transition: all 0.3s ease;
}

.timeline-item:hover {
  transform: translateX(4px);
}

.timeline-item:last-child {
  padding-bottom: 0;
}

.timeline-dot-wrapper {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 16px;
  min-width: 20px;
}

.timeline-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: #d9d9d9;
  border: 3px solid #fff;
  box-shadow: 0 0 0 2px #e8e8e8;
  z-index: 2;
  transition: all 0.3s ease;
}

.timeline-line {
  position: absolute;
  top: 12px;
  left: 50%;
  transform: translateX(-50%);
  width: 2px;
  height: calc(100% + 40px);
  background: #e8e8e8;
  z-index: 1;
}

.timeline-item.active .timeline-dot {
  background: #5e7ce0;
  border-color: #fff;
  box-shadow: 0 0 0 2px #5e7ce0, 0 0 0 4px rgba(94, 124, 224, 0.2);
  animation: pulse-dot 2s infinite;
}

.timeline-item.active .timeline-line {
  background: linear-gradient(to bottom, #5e7ce0, #e8e8e8);
}

.refund-timeline .timeline-item.active .timeline-dot {
  background: #f59e0b;
  box-shadow: 0 0 0 2px #f59e0b, 0 0 0 4px rgba(245, 158, 11, 0.2);
}

.refund-timeline .timeline-item.active .timeline-line {
  background: linear-gradient(to bottom, #f59e0b, #e8e8e8);
}

@keyframes pulse-dot {
  0%, 100% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.1);
    opacity: 0.8;
  }
}

.timeline-content {
  flex: 1;
  padding-top: 2px;
}

.timeline-text {
  color: #333;
  font-size: 14px;
  margin-bottom: 6px;
  font-weight: 500;
  line-height: 1.5;
}

.timeline-item.active .timeline-text {
  color: #5e7ce0;
  font-weight: 600;
}

.refund-timeline .timeline-item.active .timeline-text {
  color: #f59e0b;
}

.timeline-time {
  color: #999;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.timeline-time::before {
  content: '🕐';
  font-size: 12px;
}

/* 申请退货消息样式优化 */
.return-steps-container {
  background: linear-gradient(135deg, #fff5f5 0%, #fff 100%);
  border-radius: 12px;
  padding: 20px;
  margin: 12px 0;
  border: 1px solid #ffe0e0;
  box-shadow: 0 2px 8px rgba(255, 107, 53, 0.08);
}

.return-steps-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #ffe0e0;
}

.return-steps-header .icon {
  font-size: 20px;
  color: #ff6b35;
}

.return-steps-title {
  font-size: 16px;
  font-weight: 600;
  color: #ff6b35;
}

.return-steps {
  padding: 8px 0;
}

.step-item {
  display: flex;
  align-items: flex-start;
  padding: 16px;
  margin-bottom: 12px;
  background: #fff;
  border-radius: 8px;
  border-left: 3px solid #ff6b35;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.step-item:hover {
  transform: translateX(4px);
  box-shadow: 0 2px 6px rgba(255, 107, 53, 0.15);
  border-left-color: #ff8c5a;
}

.step-item:last-child {
  margin-bottom: 0;
}

.step-number {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  min-width: 28px;
  border-radius: 50%;
  background: linear-gradient(135deg, #ff6b35 0%, #ff8c5a 100%);
  color: #fff;
  font-size: 14px;
  font-weight: 600;
  margin-right: 12px;
  box-shadow: 0 2px 4px rgba(255, 107, 53, 0.3);
}

.step-content {
  display: flex;
  align-items: center;
  flex: 1;
  gap: 10px;
}

.step-icon {
  font-size: 18px;
  color: #ff6b35;
  opacity: 0.8;
}

.step-text {
  flex: 1;
  color: #333;
  font-size: 14px;
  line-height: 1.6;
  font-weight: 500;
}
</style>
